package handler

import (
	"context"
	"errors"
	pb "g-cache/biz/model/gcache"
	"strings"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
	"github.com/golang/protobuf/proto"

	"g-cache/biz/service"
)

// 全局缓存服务实例
var cacheService = service.NewCacheService()

const (
	defaultBasePath = "/_g-cache/"
)

// CacheHandler 处理缓存相关的HTTP请求
func CacheHandler(ctx context.Context, c *app.RequestContext) {
	// 检查路径前缀
	path := string(c.Request.URI().Path())
	if !strings.HasPrefix(path, defaultBasePath) {
		c.AbortWithStatusJSON(consts.StatusNotFound, map[string]string{
			"error": "unexpected path",
		})
		return
	}

	// 解析路径，格式为 /_g-cache/<group>/<key>
	parts := strings.SplitN(path[len(defaultBasePath):], "/", 2)
	if len(parts) != 2 {
		c.AbortWithStatusJSON(consts.StatusBadRequest, map[string]string{
			"error": "bad request: path format must be /" + defaultBasePath + "<group>/<key>",
		})
		return
	}

	groupName := parts[0]
	key := parts[1]

	// 从缓存服务获取数据
	value, err := cacheService.GetCacheValue(groupName, key)
	if err != nil {
		if errors.Is(err, service.ErrNoSuchGroup) {
			c.AbortWithStatusJSON(consts.StatusNotFound, map[string]string{
				"error": "no such group: " + groupName,
			})
		} else {
			c.AbortWithStatusJSON(consts.StatusInternalServerError, map[string]string{
				"error": err.Error(),
			})
		}
		return
	}

	// 序列化数据为Protobuf格式
	response := &pb.Response{Value: value}
	body, err := proto.Marshal(response)
	if err != nil {
		c.AbortWithStatusJSON(consts.StatusInternalServerError, map[string]string{
			"error": err.Error(),
		})
		return
	}

	// 返回数据
	c.Header("Content-Type", "application/octet-stream")
	c.Write(body)
}
